package com.alibaba.citrus.ots.sales.plan.repository;

import com.alibaba.citrus.ots.common.util.DateUtils;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.SalesPlanNykQueryRequest;
import com.alibaba.citrus.ots.sales.plan.sdo.SalesPlanNykSDO;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.SalesPlanNykLoadListRequest;
import com.epoch.app.bcots.model.dto.ScItemSDO;
import com.epoch.app.bcots.model.dto.SearchScItemRequest;
import com.epoch.app.bcots.salesplannyk.dto.LoadListSalesPlanNykListRequest;
import com.epoch.app.bcots.salesplannyk.model.SalesPlanNyk;
import com.epoch.app.bcots.salesplannyk.service.SalesPlanNykService;
import com.epoch.app.bcots.service.BaseDataService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class SalesPlanNykRepositoryImpl implements SalesPlanNykRepository {
    Log log = Log.getLogger(SalesPlanNykRepositoryImpl.class);

    @Resource
    private SalesPlanNykService salesPlanNykService;

    @Resource
    private BaseDataService baseDataService;

    /**
     * 分页查询
     *
     * @param salesPlanNykQueryRequest
     * @return
     */
    @Override
    public PageResult<List<SalesPlanNykSDO>> pageQuery(SalesPlanNykQueryRequest salesPlanNykQueryRequest) {
        LoadListSalesPlanNykListRequest salesPlanNykLoadListRequest = salesPlanNykQueryConverter(salesPlanNykQueryRequest);
        Result<List<SalesPlanNyk>> listResult = salesPlanNykService.loadListSalesPlanNykList(salesPlanNykLoadListRequest);
        if (Objects.isNull(listResult) || CollectionUtils.isEmpty(listResult.getResult())) {
            return PageResult.of(Lists.newArrayList(), 0);
        }
        List<String> scItemIds = listResult.getResult().stream().map(SalesPlanNyk::getScItemId).collect(Collectors.toList());
        SearchScItemRequest searchScItemRequest = new SearchScItemRequest();
        Map searchReqDTO = new HashMap();
        searchReqDTO.put("scItemIds", scItemIds);
        searchScItemRequest.setSearchReqDTO(searchReqDTO);
        searchScItemRequest.setPageNum(1);
        searchScItemRequest.setPageSize(2000);
        Result<List<ScItemSDO>> scItemResult = baseDataService.searchScItem(searchScItemRequest);
        Map<String, ScItemSDO> scItemSDOMap = Maps.newHashMap();
        if (Objects.nonNull(scItemResult) && CollectionUtils.isNotEmpty(scItemResult.getResult())) {
            scItemSDOMap = scItemResult.getResult().stream().collect(Collectors.toMap(ScItemSDO::getScItemId, o -> o));
        }
        Map<String, ScItemSDO> finalScItemSDOMap = scItemSDOMap;
        List<SalesPlanNykSDO> salesPlanNykSDOS = listResult.getResult().stream().map(salesPlanNyk -> {
            SalesPlanNykSDO salesPlanNykSDO = new SalesPlanNykSDO();
            BeanUtils.copyProperties(salesPlanNyk, salesPlanNykSDO);
//            salesPlanNykSDO.setGmtCreate(salesPlanNyk.getGmtCreate());
//            salesPlanNykSDO.setGmtModified(salesPlanNyk.getGmtModified());
            salesPlanNykSDO.setGmtCreate(salesPlanNyk.getGmt_create());
            salesPlanNykSDO.setGmtModified(salesPlanNyk.getGmt_modified());
            //获取planTime,outCreateDate
            String time = getTimeByStamp(salesPlanNyk.getPlanTime());
            if (Objects.nonNull(salesPlanNyk.getOutCreateDate())) {
                String outCreateTime = DateUtils.stampToDate2(String.valueOf(salesPlanNyk.getOutCreateDate()));
                salesPlanNykSDO.setOutCreateDate(outCreateTime);
            }
            salesPlanNykSDO.setPlanTime(time);
            ScItemSDO scItemSDO = finalScItemSDOMap.get(salesPlanNyk.getScItemId());
            if (Objects.nonNull(scItemSDO)) {
                salesPlanNykSDO.setScItemCode(scItemSDO.getOuterId());
            }

            Map<String, String> scItemInfo = new HashMap<>();
            scItemInfo.put("title", salesPlanNykSDO.getScItemName());
            if (StringUtils.isNotBlank(salesPlanNykSDO.getOuterId())){
                scItemInfo.put("subTitle", "编码：" + salesPlanNykSDO.getOuterId());
            }
            salesPlanNykSDO.setScItemInfo(scItemInfo);
            return salesPlanNykSDO;
        }).collect(Collectors.toList());
        return PageResult.of(salesPlanNykSDOS, listResult.getTotal());
    }

    private String getTimeByStamp(String stamp) {
        String planTime = "";
        if (StringUtils.isBlank(stamp)) {
            return planTime;
        }
        try {
            DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy年MM月");
            planTime = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(stamp)), ZoneId.systemDefault()));
        } catch (Exception e) {
            log.error("时间戳转日期失败");
        }
        return planTime;
    }

    private String getTimeByStamp2(String stamp) {
        String planTime = "";
        if (StringUtils.isBlank(stamp)) {
            return planTime;
        }
        try {
            DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy/MM/ss hh:mm:ss");
            planTime = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(stamp)), ZoneId.systemDefault()));
        } catch (Exception e) {
            log.error("时间戳转日期失败");
        }
        return planTime;
    }

    private LoadListSalesPlanNykListRequest salesPlanNykQueryConverter(SalesPlanNykQueryRequest salesPlanNykQueryRequest) {
        LoadListSalesPlanNykListRequest loadListRequest = new LoadListSalesPlanNykListRequest();
        BeanUtils.copyProperties(salesPlanNykQueryRequest, loadListRequest);
        String dateToStamp = DateUtils.dateToStamp(salesPlanNykQueryRequest.getPlanTime() + "-01 00:00:00");
        loadListRequest.setPlanTime(dateToStamp);
        return loadListRequest;
    }
}
